package com.ayf.payment.game.api.auths;


import com.ayf.payment.game.api.bean.AuthorizationInfo;
import com.ayf.payment.game.api.exception.AuthorizeFailedException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by liudong on 10/12/15.
 */
@Component
public abstract class AbstractAuthorization {
    @Resource
    private OAuthAuthorization oAuthAuthorization;

    /**
     * 从HttpRequest中构造AuthorizationInfo对象
     * @param request
     * @return AuthorizationInfo
     */
    public abstract AuthorizationInfo getAuthorizationInfoFromRequestHeader(HttpServletRequest request);

    /**
     * 执行授权校验
     * @param request
     * @throws AuthorizeFailedException
     * @throws IOException
     */
    public AuthorizationInfo execute(HttpServletRequest request) throws AuthorizeFailedException, IOException {
        AuthorizationInfo authorizationInfo = getAuthorizationInfoFromRequestHeader(request);
        return authorizationInfo;
    }


    /**
     * 根据授权类型获取授权对象实例
     * @param request 请求体
     * @return 授权实例
     * @throws AuthorizeFailedException
     */
    public AbstractAuthorization getInstanceByAuthType(HttpServletRequest request)
            throws AuthorizeFailedException {
        String authInfo = request.getHeader("Authorization");

        //默认为OAuth认知方式
        if (StringUtils.isBlank(authInfo)) {
            return oAuthAuthorization;
        }

        String authType = authInfo.split(" ")[0];

        if ("OAuth".equalsIgnoreCase(authType)) {
            return oAuthAuthorization;
        }

        return null;
    }
}
